package com.x.sys.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.wordnik.swagger.annotations.ApiOperation;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.x.common.bo.VerifyCode;
import com.x.sys.service.IVerifyCodeGen;
import com.x.sys.service.impl.CharVerifyCodeGenImpl;

@RestController
@RequestMapping("/verifyCode")
public class VerifyCodeController {
	 private static final Logger logger = LoggerFactory.getLogger(CharVerifyCodeGenImpl.class);
	
	@ApiOperation(value = "验证码")
	@RequestMapping
    public void  verifyCode(HttpServletRequest request, HttpServletResponse response) {
        IVerifyCodeGen iVerifyCodeGen = new CharVerifyCodeGenImpl();
        try {
            //设置长宽
            VerifyCode verifyCode = iVerifyCodeGen.generate(80, 28);
            String code1 = verifyCode.getCode();
            logger.info(code1);
            //将VerifyCode绑定session
            request.getSession().setAttribute("VerifyCode", code1);
            //设置响应头
            response.setHeader("Pragma", "no-cache");
            //设置响应头
            response.setHeader("Cache-Control", "no-cache");
            //在代理服务器端防止缓冲
            response.setDateHeader("Expires", 0);
            //设置响应内容类型
            response.setContentType("image/jpeg");
            response.getOutputStream().write(verifyCode.getImgBytes());
            response.getOutputStream().flush();
           
        } catch (IOException e) {
        	logger.info("", e);
        }
    }

@RequestMapping(value = "/checkVerify")
    public boolean CheckVerify(String code, HttpSession session) {
		String code1=(String) session.getAttribute("VerifyCode");
		
        try {
            //从session中获取随机数
            System.out.println();
            System.out.println(code);
            if (code1 == null) {
                return false;
            }
            if (code1.equalsIgnoreCase(code)) {
                System.out.println("正确的验证码");
                return true;
            } else {
                System.out.println("错误的验证码");
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
}

}
